package multiThread;

/* Avoid Deadlock Condition */

/* This program has a deadlock; try not to create such kind of program. */

class Aa implements Runnable {
	String s1, s2;

	public Aa(String s1, String s2) {
		this.s1 = s1;
		this.s2 = s2;
		Thread t = new Thread(this);
		t.start();
	}

	@Override
	public void run() {
		try {
			synchronized (s1) {
				System.out.println("s1 lock by A Calss waiting to lock for s2");
				Thread.sleep(500);
				synchronized (s2) {
					System.out.println(s1 + s2);
				}
			}
		} catch (Exception e) {
		}
	}
}

class Ba implements Runnable {
	String s1, s2;

	public Ba(String s1, String s2) {
		this.s1 = s1;
		this.s2 = s2;
		Thread t = new Thread(this);
		t.start();
	}

	@Override
	public void run() {
		try {
			synchronized (s1) { // Change s2 to s1 to avoid Deadlock
				System.out.println("s2 lock by B Calss waiting to lock for s1");
				Thread.sleep(500);
				synchronized (s2) { // Change s1 to s2 to avoid Deadlock
					System.out.println(s2 + s1);
				}
			}
		} catch (Exception e) {
		}
	}
}

public class MyThread12 {
	@SuppressWarnings("unused")
	public static void main(String args[]) {
		String s1 = "Raj";
		String s2 = "Deepa";
		Aa obj1 = new Aa(s1, s2);
		Ba obj2 = new Ba(s1, s2);
	}
}